<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #msg {
        color: red;
      }
    </style>
  </head>
  <body>
    <div id="msg"></div>
    <progress value="0" max="1" id="progress"></progress>
    <form name="form">
      <p>
        姓名
        <input type="text" name="name" value="jack" />
      </p>
      <p>
        附件
        <input type="file" name="thingfile" />
      </p>
      <p>
        <button type="button" name="saveBtn">保存</button>
      </p>
    </form>
    <script>
      const form = document.form;

      form.thingfile.onchange = function () {
        const file = form.thingfile.files[0];
        if (file === undefined) {
          msg.innerHTML = "请选择文件";
          return;
        }
        // 验证大小
        const size = file.size / 1024 / 1024;
        if (size > 1) {
          msg.innerHTML = "文件大小不能超过1M";
          return;
        }
        // 文件类型
        // 获取文件后缀名
        const ext = file.name.split(".").slice(-1)[0];
        const allowExt = ["mp4", "jpg"];

        if (allowExt.includes(ext) === false) {
          msg.innerHTML = `文件格式错误，允许的格式有${allowExt}`;
          return;
        }

        msg.innerHTML = "";
      };

      form.saveBtn.onclick = function () {
        const file = form.thingfile.files[0];
        if (file === undefined) {
          msg.innerHTML = "请选择文件";
          return;
        }
        // 验证大小
        const size = file.size / 1024 / 1024;
        if (size > 1) {
          msg.innerHTML = "文件大小不能超过1M";
          return;
        }

        // 文件类型
        // 获取文件后缀名
        const ext = file.name.split(".").slice(-1)[0];
        const allowExt = ["mp4", "jpg"];

        if (allowExt.includes(ext) === false) {
          msg.innerHTML = `文件格式错误，允许的格式有${allowExt}`;
          return;
        }

        msg.innerHTML = "";

        //收集表单信息
        const fd = new FormData();
        fd.append("name", form.name.value);
        fd.append("thingfile", form.thingfile.files[0]);

        // 将数据发送服务器
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "http://127.0.0.1:3000/upload");

        xhr.onload = function () {
          console.log(xhr.response);
        };

        xhr.upload.onloadstart = function () {
          console.log("开始上传");
        };
        xhr.upload.onprogress = function (e) {
          console.log(e.loaded, e.total);
          document.getElementById("progress").value = e.loaded / e.total;
        };
        xhr.upload.error = function (en) {
          console.log("error");
        };
        xhr.upload.onload = function (en) {
          console.log("上传成功");
        };
        xhr.upload.ontimeout = function (en) {
          console.log("上传超时");
        };
        xhr.upload.onloadend = function (en) {
          console.log("上传完成");
        };
        xhr.send(fd);
      };
    </script>
  </body>
</html>
